/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.hazardsource.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.StaffBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.hazardsource.domain.CheckListEntry;
import com.koron.hazardsource.domain.CheckListItem;
import com.koron.hazardsource.mapper.CheckListEntryMapper;
import com.koron.hazardsource.mapper.CheckListItemMapper;
import com.koron.hazardsource.service.api.CheckListService;
import com.koron.hazardsource.util.BusinessCode;
import com.koron.hazardsource.util.Immutable;
import com.koron.system.domain.DictData;
import com.koron.system.service.api.DictDataService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.InputStream;
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@PropertySource({ "classpath:flow.properties" })
public class CheckListServiceImpl implements CheckListService,AfterApprovalService,InitializingBean {
	private final static  Logger log = LoggerFactory.getLogger(CheckListServiceImpl.class);
	@Autowired
    private DictDataService dataService;

	@Autowired
	private FlowManagement flowManagement;

	@Value("${safe_standard_cl_discard}")
	private String safe_standard_cl_discard;

	@Value("${safe_standard_cl_add}")
	private String safe_standard_cl_add;

	@Value("${flow.standard.setCode}")
    private String setCode;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void afterPropertiesSet() throws Exception {
		Map map = flowManagement.getHandlers();
		map.put(CheckListEntry.class.getName(), this);
	}



	@Override
	public void processDiscard(Audit audit) {
		// TODO Auto-generated method stub

	}

	@SuppressWarnings("deprecation")
	@Override
	public void editApproval(Audit audit) {
		List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
		try(SessionFactory factory=new SessionFactory()){
			CheckListEntryMapper cleMapper=factory.getMapper(CheckListEntryMapper.class);
			CheckListItemMapper cliMapper=factory.getMapper(CheckListItemMapper.class);
			List<CheckListEntry> list = cleMapper.queryByIdList("checklist_entry_history", idList);
			for (CheckListEntry cle : list) {
				cle.setState(1);
				cle.setFstatusflag(2);
				List<CheckListItem> tempList = cliMapper.queryItemsInByEntryId("checklist_item_history", cle.getId(), null, null);
				cle.setItemList(tempList);
			}
			//保存检查表
			saveCheckList(list);
			updateFstatusflag(idList, 2);
		}catch(Exception e){
			log.error(e.getMessage());
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public void discardApproval(Audit audit) {
		List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
		try(SessionFactory factory=new SessionFactory()) {
			CheckListEntryMapper mapper = factory.getMapper(CheckListEntryMapper.class);
			List<CheckListEntry> list = mapper.queryByIdList("checklist_entry_history", idList);
			List<String> codeList = list.stream().map(CheckListEntry::getCode).collect(Collectors.toList());
			updateState(codeList, 0);
		} catch (Exception e) {
			log.error(e.getMessage());
		}

	}

	@SuppressWarnings("deprecation")
	public void saveCheckList(List<CheckListEntry> beanList) {
		try(SessionFactory factory=new SessionFactory()){
			CheckListEntryMapper cleMapper = factory.getMapper(CheckListEntryMapper.class);
			CheckListItemMapper cliMapper = factory.getMapper(CheckListItemMapper.class);
			for (CheckListEntry cle : beanList) {
				String odlId = cle.getId();
				List<CheckListItem> itemList = cle.getItemList();
				cle.setState(1);//发布状态
				Date date=new Date();
				if(StringUtils.isEmpty(cle.getCode())){
					//新增
					String id = DefaultIdGenerator.getInstance().generateLongId();
					cle.setAddTime(date);
					cle.setCode(generateCode(factory, cle));
					cle.setId(id);
					for (CheckListItem item : itemList) {
						item.setId(DefaultIdGenerator.getInstance().generateLongId());
						item.setChecklistEntryId(id);
						item.setAddTime(date);
					}
					cleMapper.insert("checklist_entry", cle);
					cleMapper.updateCode(odlId, cle.getCode());
				}else{
					String code = cle.getCode();
					CheckListEntry cleOld = cleMapper.queryByCode("checklist_entry", code);
					if(cleOld == null){//新增
						cle.setId(DefaultIdGenerator.getInstance().generateLongId());
						cle.setAddTime(date);
						cle.setCode(generateCode(factory, cle));
						for (CheckListItem item : itemList) {
							item.setId(DefaultIdGenerator.getInstance().generateLongId());
							item.setChecklistEntryId(cle.getId());
							item.setAddTime(date);
						}
						cleMapper.insert("checklist_entry", cle);
						cleMapper.updateCode(odlId, cle.getCode());
					}else{//修改
						cliMapper.deleteByEntryId("checklist_item", cleOld.getId());
						cle.setId(cleOld.getId());
						cle.setUpdateTime(date);
						for (CheckListItem item : itemList) {
							item.setId(DefaultIdGenerator.getInstance().generateLongId());
							item.setChecklistEntryId(cle.getId());
							item.setAddTime(date);
						}
						cleMapper.update("checklist_entry", cle);
					}
				}
				cliMapper.batchInsert("checklist_item", itemList);
			}
		}catch (Exception e){
			log.error(e.getMessage());
        }
	}

	@SuppressWarnings({ "rawtypes", "deprecation" })
	@Override
	public MessageBean<?> saveCheckListDraft(List<CheckListEntry> beanList, StaffBean user) {
		MessageBean<List> msg = new MessageBean<List>();
		SessionFactory factory=new SessionFactory();
		try{
			Map checkMap = addChenk(beanList);
			int code = (int) checkMap.get("code");
			String description = (String) checkMap.get("description");
			if(code != 0){
				msg.setCode(code);
				msg.setDescription(description);
				factory.close();
				return msg;
			}
			List<String> idList = new ArrayList<String>();
			CheckListEntryMapper cleMapper = factory.getMapper(CheckListEntryMapper.class);
			CheckListItemMapper cliMapper = factory.getMapper(CheckListItemMapper.class);
			for (CheckListEntry cle : beanList) {
				List<CheckListItem> itemList = cle.getItemList();
				cle.setFstatusflag(0);
				cle.setHasItems(itemList.size());
				Date date=new Date();
				cle.setAddTime(date);
				cle.setAddUser(user.getCode());
				cle.setAddUserName(user.getName());
				cle.setUpdateTime(date);
				cle.setUpdateUser(user.getCode());
				cle.setUpdateUserName(user.getName());
				if(StringUtils.isEmpty(cle.getId())){			//新增
					String id = DefaultIdGenerator.getInstance().generateLongId();
					cle.setId(id);
					for (CheckListItem cli : itemList) {
						cli.setAddTime(date);
						cli.setAddUser(user.getCode());
						cli.setChecklistEntryId(id);
						cli.setId(DefaultIdGenerator.getInstance().generateLongId());
					}
					cleMapper.insert("checklist_entry_history", cle);
					cliMapper.batchInsert("checklist_item_history", itemList);
				}else{		//修改
					//删除检查项
					cliMapper.deleteByEntryId("checklist_item_history",cle.getId());
					for (CheckListItem cli : itemList) {
						cli.setAddTime(date);
						cli.setAddUser(user.getCode());
						cli.setChecklistEntryId(cle.getId());
						cli.setId(DefaultIdGenerator.getInstance().generateLongId());
					}
					cleMapper.update("checklist_entry_history", cle);
					cliMapper.batchInsert("checklist_item_history", itemList);
				}
				idList.add(cle.getId());
			}
			factory.close();
            msg.setCode(0);
            msg.setDescription("保存成功");
            msg.setData(idList);
            return msg;
		}catch(Exception e){
			factory.close(false);
            log.error(e.getMessage());
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
		}finally {
			factory.close();
		}
	}

	@SuppressWarnings({ "unchecked" })
	@Override
	public MessageBean<?> submitCheckEntryItem(List<CheckListEntry> beanList, StaffBean user, String title,
			String note) {
		MessageBean<?> msg = saveCheckListDraft(beanList, user);
		try{
			List<String> idList;
			if(msg.getData() != null){
				idList = (List<String>) msg.getData();
			}else{
				return msg;
			}
			//启动流程
			Audit audit = new Audit(title, note, user.getName(), new Date());
    		audit.setId(DefaultIdGenerator.getInstance().generateLongId());
    		audit.setTitle(title);
    		audit.setDescription(note);
    		audit.setInitiatorCode(user.getCode());
    		audit.setTarget(CheckListEntry.class.getName());
    		audit.setTemplateKey(safe_standard_cl_add);
    		audit.setSetCode(setCode);
    		audit.setOperation(1);
    		audit.setState(1);
    		audit.setFlowType(1);
    		audit.setFlowName(Immutable.ADD_CHECK_LIST_ENTRY);
			audit.setBusinessIds(new Gson().toJson(idList));
			audit.setInitiatorAccount(user.getUserid());
			if(!flowManagement.initFlow(user, audit, new HashMap<>())){
				msg.setCode(BusinessCode.MESSAGE_CODE_FLOW_EXCEPTION);
				msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_FLOW_EXCEPTION);
			}
			 updateFstatusflag(idList, 1);  //审批中
			return msg;
		}catch(Exception e){
            return msg;
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public MessageBean<?> discard(List<String> idList, StaffBean user,String title, String note) {
		MessageBean<Boolean> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, boolean.class);
		SessionFactory factory=new SessionFactory();
		try {
			CheckListEntryMapper cleMapper = factory.getMapper(CheckListEntryMapper.class);
			CheckListItemMapper cliMapper = factory.getMapper(CheckListItemMapper.class);
			List<CheckListEntry> cleList = cleMapper.queryByIdList("checklist_entry", idList);
			List<CheckListItem> itemList = new ArrayList<CheckListItem>();
			idList = new ArrayList<String>();
			for (CheckListEntry cle : cleList) {
				cle.setFstatusflag(0);
				String id = DefaultIdGenerator.getInstance().generateLongId();
				List<CheckListItem> tempList = cliMapper.queryItemsInByEntryId("checklist_item", cle.getId(), null, null);
				for (CheckListItem item : tempList) {
					item.setId(DefaultIdGenerator.getInstance().generateLongId());
					item.setChecklistEntryId(id);
				}
				cle.setState(0);
				cle.setId(id);
				itemList.addAll(tempList);
				idList.add(id);
			}
			if(cleList.isEmpty()){
				msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
				msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
				factory.close(false);
				return msg;
			}
			cleMapper.batchInsert("checklist_entry_history", cleList);
			if(null!=itemList&&itemList.size()>0)
				cliMapper.batchInsert("checklist_item_history", itemList);
			//启动流程
			Audit audit = new Audit(title, note, user.getName(), new Date());
    		audit.setId(DefaultIdGenerator.getInstance().generateLongId());
    		audit.setTitle(title);
    		audit.setDescription(note);
    		audit.setInitiatorCode(user.getCode());
			audit.setInitiatorAccount(user.getUserid());
    		audit.setTarget(CheckListEntry.class.getName());
    		audit.setTemplateKey(safe_standard_cl_discard);
    		audit.setSetCode(setCode);
    		audit.setOperation(2);
    		audit.setState(1);
    		audit.setFlowType(1);
    		audit.setFlowName(Immutable.DISCARD_CHECK_LIST_ENTRY);
			audit.setBusinessIds(new Gson().toJson(idList));
			if(!flowManagement.initFlow(user, audit, new HashMap<>())){
				factory.close(false);
				msg.setCode(BusinessCode.MESSAGE_CODE_FLOW_EXCEPTION);
				msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_FLOW_EXCEPTION);
				return msg;
			}
			factory.close();
			return msg;
		}catch (Exception e) {
			msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
			factory.close(false);
			return msg;
		}finally {
			if (null != factory){
				factory.close();
			}
		}
	}


	@SuppressWarnings("deprecation")
	@Override
	public MessageBean<?> detailsByCode(String code) {
		MessageBean<CheckListEntry> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, CheckListEntry.class);
		try(SessionFactory factory=new SessionFactory();){
			CheckListEntryMapper cleMapper = factory.getMapper(CheckListEntryMapper.class);
			CheckListItemMapper cliMapper = factory.getMapper(CheckListItemMapper.class);
			CheckListEntry cle = cleMapper.queryByCode("checklist_entry", code);
			if(cle == null){
				return msg;
			}
			cle.setItemList(cliMapper.queryItemsInByEntryId("checklist_item", cle.getId(), null, null));
			msg.setData(cle);
		}catch (Exception e) {
    		msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
		}
		return msg;
	}

	@SuppressWarnings({ "deprecation" })
	@Override
	public CheckListEntry details(String tableName,String itemTable, String id) {
		CheckListEntry cle = new CheckListEntry();
		try(SessionFactory factory=new SessionFactory()){
			CheckListEntryMapper cleMapper = factory.getMapper(CheckListEntryMapper.class);
			cle = cleMapper.queryOne(tableName, id);
			if(cle == null){
				return cle;
			}
			CheckListItemMapper cliMapper = factory.getMapper(CheckListItemMapper.class);
			List<CheckListItem> itemList = cliMapper.queryItemsInByEntryId(itemTable, id, null, null);
			cle.setItemList(itemList);
		}
		return cle;
	}

	@SuppressWarnings({ "deprecation" })
	@Override
	public List<CheckListEntry> list(String table,String businessTypeId, String name, String checklistEntryTypeId, Integer start,
			Integer rows) {
		try(SessionFactory factory=new SessionFactory()){
			List<CheckListEntry> list = factory.getMapper(CheckListEntryMapper.class).queryByCondition(table, businessTypeId, name, checklistEntryTypeId, start, rows);
			return list;
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public Integer count(String table, String businessTypeId, String name, String checklistEntryTypeId) {
		try(SessionFactory factory=new SessionFactory()){
			Integer count = factory.getMapper(CheckListEntryMapper.class).countByCondition(table, businessTypeId, name, checklistEntryTypeId);
			return count;
		}
	}

	@SuppressWarnings("deprecation")
	public void delete(List<String> idList){
		try(SessionFactory factory=new SessionFactory()){
			CheckListEntryMapper mapper = factory.getMapper(CheckListEntryMapper.class);
			mapper.batchDelete("checklist_entry_history", idList);
			CheckListItemMapper cliMapper = factory.getMapper(CheckListItemMapper.class);
			for (String string : idList) {
				cliMapper.deleteByEntryId("checklist_item_history", string);
			}
		}
	}

	@SuppressWarnings({ "deprecation", "unchecked", "resource" })
	@Override
	public MessageBean<?> importExcel(StaffBean user, String checkCode, String checklistEntryTypeId, String businessTypeId,
			String title, String note,MultipartFile file) {
		MessageBean<?> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, boolean.class);
		if(file == null){
			msg.setCode(-1);
			msg.setDescription("无上传文件");
			return msg;
		}
		InputStream inputStream = null;
		SessionFactory factory=new SessionFactory();
		try{
			inputStream = file.getInputStream();
			CheckListEntry cle = new CheckListEntry();
			XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
			// 取第一个sheet页
			XSSFSheet sheet = workbook.getSheetAt(0);
			Cell checkEntryNameandCodeCell = sheet.getRow(0).getCell(0);
			if (checkEntryNameandCodeCell == null) {
				msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
				msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
				factory.close(false);
				return msg;
			}
			String checkEntryName=getCellValue(checkEntryNameandCodeCell); //名称
			if(StringUtils.isEmpty(checklistEntryTypeId) || StringUtils.isEmpty(businessTypeId)){
				msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
				msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
				factory.close(false);
				return msg;
			}
			cle.setName(checkEntryName);
			cle.setState(0);
			cle.setAddTime(new Date());
			cle.setAddUser(user.getCode());
			cle.setAddUserName(user.getName());
			CheckListEntryMapper mapper = factory.getMapper(CheckListEntryMapper.class);
			if(StringUtils.isEmpty(checkCode)){
				if(StringUtils.isEmpty(checklistEntryTypeId) || StringUtils.isEmpty(businessTypeId)){
					msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
					msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
					factory.close(false);
					return msg;
				}
				cle.setBusinessTypeId(businessTypeId);
				cle.setChecklistEntryTypeId(checklistEntryTypeId);
				cle.setCode("");
			}else{
				CheckListEntry oldCle = mapper.queryByCode("checklist_entry", checkCode);
				if(oldCle == null){
					if(StringUtils.isEmpty(checklistEntryTypeId) || StringUtils.isEmpty(businessTypeId)){
						msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
						msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
						factory.close(false);
						return msg;
					}
					cle.setBusinessTypeId(businessTypeId);
					cle.setChecklistEntryTypeId(checklistEntryTypeId);
					cle.setCode("");
				}else{
					cle.setBusinessTypeId(oldCle.getBusinessTypeId());
					cle.setChecklistEntryTypeId(oldCle.getChecklistEntryTypeId());
					cle.setCode(checkCode);
				}
			}
			List<CheckListItem> cliList = new ArrayList<>();
			//解析检查项
			for (int rowNum = 7; rowNum <= sheet.getLastRowNum();) {
				Row row = sheet.getRow(rowNum);
				parseCheckItems(row,user.getCode(),new Date(),cle.getId(),cliList);
				rowNum++;
			}
			List<CheckListEntry> beanList = new ArrayList<CheckListEntry>();
			cle.setItemList(cliList);
			cle.setHasItems(cliList.size());
			beanList.add(cle);
			msg = saveCheckListDraft(beanList, user);
			List<String> idList = new ArrayList<String>();
			if(msg.getData() != null){
				idList = (List<String>) msg.getData();
			}else{
				factory.close(false);
				return msg;
			}
			//启动流程
			Audit audit = new Audit(title, note, user.getName(), new Date());
    		audit.setId(DefaultIdGenerator.getInstance().generateLongId());
    		audit.setTitle(title);
    		audit.setDescription(note);
    		audit.setInitiatorCode(user.getCode());
    		audit.setTarget(CheckListEntry.class.getName());
    		audit.setTemplateKey(safe_standard_cl_add);
    		audit.setSetCode(setCode);
    		audit.setOperation(1);
    		audit.setState(1);
    		audit.setFlowType(1);
    		audit.setFlowName(Immutable.ADD_CHECK_LIST_ENTRY);
			audit.setBusinessIds(new Gson().toJson(idList));
			if(!flowManagement.initFlow(user, audit, new HashMap<>())){
				delete(idList);
				msg.setCode(BusinessCode.MESSAGE_CODE_FLOW_EXCEPTION);
				msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_FLOW_EXCEPTION);
				factory.close(false);
				return msg;
			}
			factory.close();
			return msg;
		}catch (Exception e) {
			factory.close(false);
			msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
			return msg;
		}finally {
			if (null != factory){
				factory.close();
			}
		}
	}

	private List<CheckListItem> parseCheckItems(Row row, String userCode, Date date, String cleId,List<CheckListItem> cliList)
			throws Exception {
		String keyword = getCellValue(row.getCell(0));
		String itemIndex = getCellValue(row.getCell(1));
		String itemName = getCellValue(row.getCell(3));
		CheckListItem cli = new CheckListItem();
		cli.setChecklistEntryId(cleId);
		double d = Double.parseDouble(itemIndex);
		cli.setItemIndex(Double.valueOf(d).intValue());
		cli.setName(itemName);
		cli.setKeyword(keyword);
		cliList.add(cli);
		return cliList;
	}


	@SuppressWarnings({ "rawtypes", "unchecked" })
	private Map addChenk(List<CheckListEntry> beanList){
		Map map = new HashMap();
		for (CheckListEntry cle : beanList) {
			if(cle == null){
				map.put("code", 22001);
        		map.put("description", "未填写检查表无法保存");
        		return map;
			}
			List<CheckListItem> cliList = cle.getItemList();
			if(cliList == null){
				map.put("code", 22001);
        		map.put("description", "未填写检查项无法保存");
        		return map;
			}
			if(StringUtils.isEmpty(cle.getName())){
				map.put("code", 22001);
        		map.put("description", "检查表名称不能为空");
        		return map;
			}
			if(StringUtils.isEmpty(cle.getChecklistEntryTypeId())){
				map.put("code", 22001);
        		map.put("description", "检查表类型不能为空");
        		return map;
			}
			for (CheckListItem item : cliList) {
				if(StringUtils.isEmpty(item.getName())){
					map.put("code", 22001);
	        		map.put("description", "检查项名称不能为空");
	        		return map;
				}
				/*if(StringUtils.isEmpty(item.getKeyword())){
					map.put("code", 22001);
	        		map.put("description", "检查项类别不能为空");
	        		return map;
				}*/
			}
		}
		map.put("code", 0);
		map.put("description", "校验成功");
		return map;
	}

	@SuppressWarnings({ "deprecation" })
	private void updateState(List<String> codeList,int state){
    	try(SessionFactory factory=new SessionFactory();){
    		CheckListEntryMapper mapper=factory.getMapper(CheckListEntryMapper.class);
    		mapper.updateState(codeList, state);
    	}catch (Exception e) {
			log.error(e.getMessage());
		}
    }
	@SuppressWarnings("deprecation")
	private void updateFstatusflag(List<String> idList,int fstatusflag){
		try(SessionFactory factory=new SessionFactory();){
			CheckListEntryMapper mapper=factory.getMapper(CheckListEntryMapper.class);
			mapper.updateFstatusflag(idList, fstatusflag);
		}catch (Exception e) {
			log.error(e.getMessage());
		}
	}
	private String generateCode(SessionFactory factory,CheckListEntry cle){
		CheckListEntryMapper mapper = factory.getMapper(CheckListEntryMapper.class);
    	Integer count = 0;
    	String businessValue = "";
    	String hazardValue = "";
    	DictData businessType = dataService.queryOne(cle.getBusinessTypeId()).getData();
		if(businessType != null){
			businessValue = businessType.getDictValue();
		}
    	DictData hazardType = dataService.queryOne(cle.getChecklistEntryTypeId()).getData();
    	if(hazardType != null){
    		hazardValue = hazardType.getDictValue();
    	}
    	count = mapper.countByCondition("checklist_entry", cle.getBusinessTypeId(), null, cle.getChecklistEntryTypeId());
    	count++;
		NumberFormat nf = NumberFormat.getInstance();
		nf.setGroupingUsed(false);
		nf.setMaximumIntegerDigits(3); // 设置最大整数位数
		nf.setMinimumIntegerDigits(3); // 设置最小整数位数
		StringBuilder sb = new StringBuilder();
		sb.append("W").append(businessValue).append(hazardValue).append(nf.format(count));
		return sb.toString();
    }

	/**
	 * 获取单元格的值
	 *
	 * @param cell
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public String getCellValue(Cell cell) {
		if (cell == null)
			return "";
		if (cell.getCellTypeEnum() == CellType.STRING) {
			return cell.getStringCellValue();
		} else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
			return String.valueOf(cell.getBooleanCellValue());
		} else if (cell.getCellTypeEnum() == CellType.FORMULA) {
			return cell.getCellFormula();
		} else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
			return String.valueOf(cell.getNumericCellValue());
		} else {
			return "";
		}
	}

	/**
	 * 合并单元格处理,获取合并行
	 *
	 * @param sheet
	 * @return List<CellRangeAddress>
	 */
	public List<CellRangeAddress> getCombineCell(XSSFSheet sheet) {
		List<CellRangeAddress> list = new ArrayList<CellRangeAddress>();
		// 获得一个 sheet 中合并单元格的数量
		int sheetmergerCount = sheet.getNumMergedRegions();
		// 遍历所有的合并单元格
		for (int i = 0; i < sheetmergerCount; i++) {
			// 获得合并单元格保存进list中
			CellRangeAddress ca = sheet.getMergedRegion(i);
			list.add(ca);
		}
		return list;
	}
	/*private CellRangeAddress getCellRange(List<CellRangeAddress> listCombineCell, Cell cell) {
		int firstC = 0, lastC = 0, firstR = 0, lastR = 0;
		for (CellRangeAddress ca : listCombineCell) {
			// 获得合并单元格的起始行, 结束行, 起始列, 结束列
			firstC = ca.getFirstColumn();
			lastC = ca.getLastColumn();
			firstR = ca.getFirstRow();
			lastR = ca.getLastRow();
			if (cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR) {
				if (cell.getColumnIndex() >= firstC && cell.getColumnIndex() <= lastC) {
					return ca;
				}
			}
		}
		return null;
	}*/

	@SuppressWarnings({ "deprecation", "rawtypes" })
	@Override
	public MessageBean<?> getDraftList(StaffBean user) {
		MessageBean<List> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, List.class);
		try(SessionFactory factory=new SessionFactory();){
			CheckListEntryMapper cleMapper = factory.getMapper(CheckListEntryMapper.class);
			CheckListItemMapper cliMapper = factory.getMapper(CheckListItemMapper.class);
			List<CheckListEntry> list = cleMapper.getDraftList(user.getCode());
			for (CheckListEntry cle : list) {
				cle.setItemList(cliMapper.queryItemsInByEntryId("checklist_item_history", cle.getId(), null, null));
			}
			msg.setData(list);
		}catch (Exception e) {
    		msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
		}
		return msg;
	}

	@SuppressWarnings({ "deprecation", "rawtypes" })
	@Override
	public MessageBean<?> getProcessData(String ids) {
		MessageBean<List> msg = MessageBean.create(0, "success", List.class);
        try (SessionFactory factory = new SessionFactory();) {
        	List<String> idList = JSONObject.parseArray(ids, String.class);
        	CheckListEntryMapper cleMapper = factory.getMapper(CheckListEntryMapper.class);
			CheckListItemMapper cliMapper = factory.getMapper(CheckListItemMapper.class);
            List<CheckListEntry> list = cleMapper.queryByIdList("checklist_entry_history", idList);
            for (CheckListEntry cle : list) {
                cle.setItemList(cliMapper.queryItemsInByEntryId("checklist_item_history", cle.getId(), null, null));
            }
            msg.setData(list);
        } catch (Exception e) {
        	msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        }
        return msg;
	}

	@SuppressWarnings({ "deprecation", "rawtypes" })
	@Override
	public MessageBean<?> getHistoryList(String code) {
		MessageBean<List> msg = MessageBean.create(0, "success", List.class);
        try (SessionFactory factory = new SessionFactory()) {
        	CheckListEntryMapper cleMapper = factory.getMapper(CheckListEntryMapper.class);
			CheckListItemMapper cliMapper = factory.getMapper(CheckListItemMapper.class);
            List<CheckListEntry> list = cleMapper.queryHstory(code);
            for (CheckListEntry cle : list) {
            	cle.setItemList(cliMapper.queryItemsInByEntryId("checklist_item_history", cle.getId(), null, null));
            }
            msg.setData(list);
        } catch (Exception e) {
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        }
        return msg;
	}

	@SuppressWarnings("deprecation")
	@Override
	public MessageBean<?> deleteDraft(String id) {
		MessageBean<?> msg = MessageBean.create(0, "success", void.class);
		SessionFactory factory = new SessionFactory();
        try{
        	CheckListEntryMapper cleMapper = factory.getMapper(CheckListEntryMapper.class);
			CheckListItemMapper cliMapper = factory.getMapper(CheckListItemMapper.class);
			cleMapper.deleteDraft(id);
			cliMapper.deleteDraft(id);
			factory.close();
        } catch (Exception e) {
        	factory.close(false);
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        }
        return msg;
	}


	@Override
	public void reject(Audit audit, List<String> userIdList) {
		// TODO 流程驳回操作
	}

	@Override
	public void passApproval(Integer operation, Audit audit) {
		// TODO 流程提交成功操作
	}
}
